package com.leyou.item.service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.leyou.common.constants.MQConstants;
import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exceptions.LyException;
import com.leyou.common.utils.BeanHelper;
import com.leyou.common.vo.PageResult;
import com.leyou.item.dto.*;
import com.leyou.item.entity.Sku;
import com.leyou.item.entity.Spu;
import com.leyou.item.entity.SpuDetail;
import com.leyou.item.mapper.SkuMapper;
import com.leyou.item.mapper.SpuDetailMapper;
import com.leyou.item.mapper.SpuMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author 虎哥
 */
@Slf4j
@Service
public class GoodsService {

    @Autowired
    private SpuMapper spuMapper;

    @Autowired
    private SpuDetailMapper detailMapper;

    /*
    SELECT *
    FROM tb_spu
    WHERE `name` LIKE "%H%" AND saleable = 1
    ORDER BY update_time DESC
    LIMIT 0, 5
     */
    public PageResult<SpuDTO> querySpuByPage(String key, Integer page, Integer rows, Boolean saleable) {
        // 1.分页， LIMIT 0, 5
        Page result = PageHelper.startPage(page, rows);
        // 2.准备过滤条件
        Example example = new Example(Spu.class);
        Example.Criteria criteria = example.createCriteria();
        // 2.1.关键字过滤条件, `name` LIKE "%H%" AND saleable = 1
        if (StringUtils.isNotBlank(key)) {
            criteria.andLike("name", "%" + key + "%");
        }
        // 2.2.上下架的过滤
        if (saleable != null) {
            criteria.andEqualTo("saleable", saleable);
        }
        // 2.3.排序条件
        example.setOrderByClause("update_time DESC");
        // 3.查询结果
        List<Spu> list = spuMapper.selectByExample(example);
        if (CollectionUtils.isEmpty(list)) {
            throw new LyException(ExceptionEnum.GOODS_NOT_FOUND);
        }
        // 4.封装结果并返回
        // 4.1.转换DTO
        List<SpuDTO> items = BeanHelper.copyWithCollection(list, SpuDTO.class);

        // 4.2.处理分类和品牌的名称
        handleCategoryAndBrandName(items);

        // 4.3.封装并返回
        return new PageResult<>(result.getTotal(), result.getPages(), items);
    }

    @Autowired
    private BrandService brandService;

    @Autowired
    private CategoryService categoryService;

    private void handleCategoryAndBrandName(List<SpuDTO> spuDTOList) {
        // 取出所有品牌的id
        List<Long> brandIds = spuDTOList.stream().map(SpuDTO::getBrandId).collect(Collectors.toList());
        // 查询品牌
        List<BrandDTO> brands = brandService.queryByIds(brandIds);
        // 把品牌变成一个map，key是brand的id，值是brand的name
        Map<Long, String> brandNames = brands.stream()
                .collect(Collectors.toMap(BrandDTO::getId, BrandDTO::getName));
        /*Map<Long, String> brandNames = new HashMap<>();
        for (BrandDTO brand : brands) {
            brandNames.put(brand.getId(), brand.getName());
        }*/

        for (SpuDTO spu : spuDTOList) {

            // 添加分类名称
            List<Long> categoryIds = spu.getCategoryIds();
            /*List<CategoryDTO> categoryDTOList = categoryService.queryByIds(categoryIds);
            StringBuilder sb = new StringBuilder();
            for (CategoryDTO categoryDTO : categoryDTOList) {
                sb.append(categoryDTO.getName()).append("/");
            }
            sb.deleteCharAt(sb.length() - 1);*/
            String categoryName = categoryService.queryByIds(categoryIds)
                    .stream()
                    .map(CategoryDTO::getName)
                    .collect(Collectors.joining("/"));
            spu.setCategoryName(categoryName);

            // 添加品牌的名称
            spu.setBrandName(brandNames.get(spu.getBrandId()));
        }
    }

    @Autowired
    private SkuMapper skuMapper;

    @Transactional
    public void saveGoods(SpuDTO spuDTO) {
        try {
            // 1.新增spu
            Spu spu = BeanHelper.copyProperties(spuDTO, Spu.class);
            // 默认是下架
            spu.setSaleable(false);
            spuMapper.insertSelective(spu);

            // 2.新增spuDetail
            SpuDetailDTO detailDTO = spuDTO.getSpuDetail();
            SpuDetail spuDetail = BeanHelper.copyProperties(detailDTO, SpuDetail.class);
            spuDetail.setSpuId(spu.getId());
            detailMapper.insertSelective(spuDetail);

            // 3.新增sku
            saveSku(spuDTO, spu);
        } catch (Exception e) {
            log.error("新增商品失败，原因：{}", e.getMessage());
            // 新增操作失败！
            throw new LyException(ExceptionEnum.INSERT_OPERATION_FAIL);
        }
    }

    @Autowired
    private AmqpTemplate amqpTemplate;

    @Transactional
    public void updateSaleable(Long id, Boolean saleable) {
        try {
            // 1.更新spu的上下架
            Spu record = new Spu();
            record.setId(id);
            record.setSaleable(saleable);
            int count = spuMapper.updateByPrimaryKeySelective(record);
            if (count != 1) {
                // 无效的请求参数
                throw new RuntimeException("商品的id不存在！");
            }
            // 2.更新sku
            // 2.1.要更新的数据
            Sku sku = new Sku();
            sku.setEnable(saleable);
            // 2.2.更新的条件
            Example example = new Example(Sku.class);
            example.createCriteria().andEqualTo("spuId", id);
            skuMapper.updateByExampleSelective(sku, example);

            // 发送消息
            String routingKey = saleable ? MQConstants.RoutingKey.ITEM_UP_KEY : MQConstants.RoutingKey.ITEM_DOWN_KEY;
            amqpTemplate.convertAndSend(MQConstants.Exchange.ITEM_EXCHANGE_NAME, routingKey, id);
        } catch (RuntimeException e) {
            log.error("更新商品上下架属性失败，原因：{}", e.getMessage());
            throw new LyException(ExceptionEnum.UPDATE_OPERATION_FAIL);
        }
    }

    public SpuDetailDTO queryDetailBySpuId(Long id) {
        SpuDetail spuDetail = detailMapper.selectByPrimaryKey(id);
        if (spuDetail == null) {
            throw new LyException(ExceptionEnum.GOODS_NOT_FOUND);
        }
        return BeanHelper.copyProperties(spuDetail, SpuDetailDTO.class);
    }

    public List<SkuDTO> querySkuBySpuId(Long id) {
        Sku record = new Sku();
        record.setSpuId(id);
        List<Sku> list = skuMapper.select(record);
        if (CollectionUtils.isEmpty(list)) {
            throw new LyException(ExceptionEnum.GOODS_NOT_FOUND);
        }
        return BeanHelper.copyWithCollection(list, SkuDTO.class);
    }

    @Transactional
    public void updateGoods(SpuDTO spuDTO) {
        try {
            Long spuId = spuDTO.getId();
            if (spuId == null) {
                throw new RuntimeException("商品id不能为空！");
            }
            // 1.查询sku
            Sku record = new Sku();
            record.setSpuId(spuId);
            int count = skuMapper.selectCount(record);
            if (count != 0) {
                // 2.删除sku
                skuMapper.delete(record);
            }

            // 3.更新spu
            Spu spu = BeanHelper.copyProperties(spuDTO, Spu.class);
            // 不允许修改上下架值
            spu.setSaleable(null);
            spu.setCreateTime(null);
            count = spuMapper.updateByPrimaryKeySelective(spu);
            if (count != 1) {
                throw new RuntimeException("商品id不正确！");
            }
            // 4.更新spuDetail
            SpuDetailDTO detailDTO = spuDTO.getSpuDetail();
            SpuDetail spuDetail = BeanHelper.copyProperties(detailDTO, SpuDetail.class);
            detailMapper.updateByPrimaryKeySelective(spuDetail);

            // 5.新增sku表
            saveSku(spuDTO, spu);
        } catch (RuntimeException e) {
            log.error("更新商品失败，原因：{}", e.getMessage());
            throw new LyException(ExceptionEnum.UPDATE_OPERATION_FAIL);
        }
    }

    private void saveSku(SpuDTO spuDTO, Spu spu) {
        List<SkuDTO> dtoList = spuDTO.getSkus();
        List<Sku> skuList = BeanHelper.copyWithCollection(dtoList, Sku.class);
        for (Sku sku : skuList) {
            sku.setSpuId(spu.getId());
            sku.setEnable(false);
        }
        // 批量新增
        skuMapper.insertList(skuList);
    }

    public SpuDTO querySpuById(Long id) {
        // 根据主键查询SPU
        Spu spu = spuMapper.selectByPrimaryKey(id);
        if (spu == null) {
            throw new LyException(ExceptionEnum.GOODS_NOT_FOUND);
        }
        SpuDTO spuDTO = BeanHelper.copyProperties(spu, SpuDTO.class);
        // 查询spuDetail
        spuDTO.setSpuDetail(queryDetailBySpuId(id));
        // 查询sku集合
        spuDTO.setSkus(querySkuBySpuId(id));
        return spuDTO;
    }

    public List<SkuDTO> querySkuByIds(List<Long> ids) {
        List<Sku> list = skuMapper.selectByIdList(ids);
        if (CollectionUtils.isEmpty(list)) {
            throw new LyException(ExceptionEnum.GOODS_NOT_FOUND);
        }
        return BeanHelper.copyWithCollection(list, SkuDTO.class);
    }

    @Transactional
    public void minusStock(Map<Long, Integer> skuMap) {
        for (Map.Entry<Long, Integer> entry : skuMap.entrySet()) {
            // 更新库存
            try {
                int count = skuMapper.minusStock(entry.getKey(), entry.getValue());
                if (count != 1) {
                    throw new RuntimeException("库存不足");
                }
            } catch (RuntimeException e) {
                throw new LyException(ExceptionEnum.STOCK_NOT_ENOUGH);
            }
        }
    }
}
